// 创建文章接口
import joi from 'joi'
import pool from '@/server/db'
import { ResultSetHeader } from 'mysql2'

export default defineEventHandler(async event => {
  // 判断用户是否登录
  if (!event.context.userinfo) return r('请登录')
  const { uid } = event.context.userinfo

  // 数据校验
  const body = await readBody(event)
  const schema = joi.object({
    notebookID: joi.number().required(),
    title: joi.string().required(),
    content: joi.string().required(),
    state: joi.number().required(),
  })
  try {
    const value = schema.validate(body)
  } catch (error) {
    return r('name不能为空')
  }

  // 创建文章
  try {
    const [rows] = await pool.execute(
      'INSERT INTO `notes` (`title`, `content_md`, `state`, `uid`) value (?,?,?,?)',
      [body.title, body.content, body.state, uid]
    )
    if ((rows as ResultSetHeader).affectedRows === 0) {
      return r('创建文章失败')
    }
    // 关联文集表
    const [rows2] = await pool.execute(
      'INSERT INTO `notebook_notes` (`notebook_id`, `note_id`) value (?,?)',
      [body.notebookID, (rows as { insertId: number }).insertId]
    )
    if ((rows as ResultSetHeader).affectedRows === 0) {
      return r('关联文集表失败')
    }
    return r('创建成功', 1)
  } catch (error) {
    return r('文章创建失败:' + error)
  }
})
